const db = require('./db')

// 图书管理的模块
function showList(req, res) {
    // 执行查询
    db.query('select *,(select count(*) from history where book_id = books.id) as histroy_count from books  where status = 1', function (err, rows) {
        if (err) {
            console.log(err)
            res.end(err.message);
        } else {
            req.renderTemplate('books.ejs', {
                bookArray: rows
            })
        }
    })
}
// 保存图书
function saveBook(req, res) {
    /// 直接获取保存的数据
    console.log(req.params)
    const p = req.params;
    const sql = `insert into books (name,isbn,price,author,publisher,category)
    values ('${p.name}','${p.isbn}','${p.price}','${p.author}','${p.publisher}','${p.category}')`;
    db.query(sql, function (err, result) {
        res.writeHead(200, {
            'Content-Type': 'text/html;charset=utf-8'
        })
        if (err) {
            res.end('保存失败');
        } else {
            res.end(`保存成功,2秒后自动进入列表
            <script>
                setTimeout(()=>{
                    location.href = "/";
                },2000)
            </script>
            `)
        }
    })
}

function modifyBook(req, res) {
    const id = req.params.id;
    db.query(`select * from books where id='${id}' where status = 1`, (err, bookArray) => {
        if (err) {
            res.writeHead(500);
            console.log(err)
            res.end(err.message);
        } else {
            res.writeHead(200, {
                'Content-Type': 'text/html;charset=utf-8'
            });
            // 没有对应id的数据
            if (bookArray.length == 0) {
                res.end('没有找到修改的图书数据');
            } else {
                console.log(bookArray);
                req.renderTemplate('editbook.ejs', {
                    bookData: bookArray[0]
                })
            }

        }
    })
}

// 更新数据
function updateBook(req, res) {
    const book = req.params;
    db.query(`UPDATE books SET name='${book.name}', isbn='${book.isbn}', 
    price='${book.price}', author='${book.author}', publisher='${book.publisher}',
     category='${book.category}' WHERE  id=${book.id}`, (err, bookArray) => {
        if (err) {
            res.writeHead(500);
            console.log(err)
            res.end(err.message);
        } else {
            res.writeHead(200, {
                'Content-Type': 'text/html;charset=utf-8'
            });
            res.end(`更新数据成功!
                <script>
                    setTimeout(()=>{
                        location.href= "/";
                    },2000)
                </script>
            `)
        }
    })
}
function deleteBook(req, res) {
    const id = req.params.id;
    // 讲status设置为0表示删除该数据
    db.query(`update books set status = 0 where id='${id}'`, (err) => {
        if (err) {
            res.writeHead(500);
            console.log(err)
            res.end(err.message);
        } else {
            res.writeHead(200, {
                'Content-Type': 'text/html;charset=utf-8'
            });
            res.end(`<script>location.href= "/";</script>`)
        }
    });
}
/**
 * @param {{url:String}} req 
 * @param {{write:Function,end:Function}} res 
 */
function process(req, res) {
    const url = req.url.toLowerCase();
    if (url == '/book/all' || url == '/') {
        showList(req, res);
    } else if (url == '/book/save') {
        saveBook(req, res);// 保存图书
    } else if (url.indexOf('/book/modify') == 0) {
        modifyBook(req, res);// 修改图书
    } else if (url.indexOf('/book/update') == 0) {
        updateBook(req, res);// 修改图书
    }else if (url.indexOf('/book/delete') == 0) {
        deleteBook(req, res);// 删除图书
    }
}
module.exports = {
    process
}